package com.study.ai;

import java.net.*;
import java.io.*;

public class ChatGPTAPIExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://api.openai.com/v1/engines/davinci-codex/completions");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Authorization", "Bearer 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");

            String input = "{\"prompt\": \"Hello, ChatGPT!\", \"max_tokens\": 5}";

            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();
            os.write(input.getBytes());
            os.flush();
            os.close();

            int responseCode = con.getResponseCode();
            System.out.println("Response code: " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println("Response: " + response.toString());
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}
